#https://segmentfault.com/a/1190000015777243
import cv2
import numpy as np

capture=cv2.VideoCapture('vtest.avi')

#while capture.isOpened():
if 1:
    _,src_frame=capture.read()


    #获取角点
    old_gray=cv2.cvtColor(src_frame,cv2.COLOR_BGR2GRAY)
    feature_p=dict(maxCorners=255,
                   qualityLevel=0.01
                   ,minDistance=3,blockSize=5)
    #p0=cv2.goodFeaturesToTrack(old_gray,mask=None,**feature_p)
    p0=cv2.goodFeaturesToTrack(old_gray,255,0.01,10)
    #for x,y in np.float32(p0).reshape(-1,2):
    #    old_gray=cv2.circle(src_frame,(x,y),3,(0,0,255),-1)

    #创建一个遮罩:
    mask=np.zeros_like(src_frame)
    #计算光流
    color = np.random.randint(0,255,(255,3))
lk_params = dict( winSize  = (15,15),
                  maxLevel = 2,
                  criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))
while 1:
    _,frame=capture.read()
    frame_gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    p1,st,err=cv2.calcOpticalFlowPyrLK(old_gray,frame_gray,p0,None,**lk_params)
    #选择特征点
    good_old=p0[st==1]
    good_new=p1[st==1]
    for i,(new,old) in enumerate(zip(good_new,good_old)):
        a,b = new.ravel()
        c,d = old.ravel()
        mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)
        frame = cv2.circle(frame,(a,b),5,color[i].tolist(),-1)
    img = cv2.add(frame,mask)
    cv2.imshow('xx',img)
    old_gray = frame_gray.copy()
    p0 = good_new.reshape(-1,1,2)
    if cv2.waitKey(300) & 0xFF == ord('q'):
        break
